package cn.itcast.bos.service.system.impl;

import cn.itcast.bos.dao.system.RoleRepositor;
import cn.itcast.bos.domain.system.Menu;
import cn.itcast.bos.domain.system.Permission;
import cn.itcast.bos.domain.system.Role;
import cn.itcast.bos.domain.system.User;
import cn.itcast.bos.service.system.MenuService;
import cn.itcast.bos.service.system.PermissionService;
import cn.itcast.bos.service.system.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleRepositor roleRepositor;        //角色dao
    @Autowired
    private PermissionService permissionService;//权限dao
    @Autowired
    private MenuService menuService;            //菜单dao

    @Override
    public List<Role> findByUser(User user) {
//        List<Role> list = roleRepositor.findRoleByUser(user.getId());
        if (user.getUsername().equalsIgnoreCase("admin")){
            return roleRepositor.findAll();
        }else {
            return roleRepositor.findRoleByUser(user.getId());
        }
    }

    @Override
    public List<Role> findAll() {
        return roleRepositor.findAll();
    }

    @Override
    public void save(Role model, String[] permissionIds, String menuIds) {
        roleRepositor.save(model);
        //关联权限
        if(permissionIds != null){
            for (String permissionId : permissionIds) {
                Permission permission = permissionService.findOne(Integer.parseInt(permissionId));
                model.getPermissions().add(permission);
            }
        }

        //关联菜单
        if (menuIds != null){
            String[] split = menuIds.split(",");
            for (String s : split) {
                Menu menu = menuService.findOne(Integer.parseInt(s));
                model.getMenus().add(menu);
            }
        }


    }


}
